﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using System;
using Elixis;
using Elixis.EncryptionOptions;

public class chengyuManager : MonoBehaviour {
    public static chengyuManager Instance;
    public UITexture res;
    public GameObject Answer1, Answer2, Answer3, Answer4;
    private string[] answers;
    public int answersLength;
    public int answerK = 0;
    public GameObject disturbItem;
    public GameObject answerItem;
    public GameObject disturbPanel;
    public GameObject answerPanel;
    public Dictionary<string, ConfigDataStyle> configDictionary = new Dictionary<string, ConfigDataStyle>();
    public int configDictionaryLength;
    public string Answer;
    public UILabel CoinNum;
    public GameObject TruePanel;
    private int GetIntId; //成语猜图关卡    
    private int ConfigFirstId;   
    private int width;
    private int height;
    private int GetIntCoin;
    private int timer = 0;
    public UILabel DownTimer;
    public bool QiangDao = false;
    public UILabel CurrentLevel;
    private List<string> DisturbList;
    private static AESEncryptor fAesEncrypt = new AESEncryptor("bytes", AESBits.BITS256);
    // Use this for initialization
    void Awake()
    {
        InitDisturb();
        //PlayerPrefs.DeleteAll();
        Instance = this;
        answerPanel.GetComponent<GameObject>();
    }
    void Start () {      
       
        readConfig();
        //if (PlayerPrefs.GetInt("id"))
        //{
        //    PlayerPrefs.SetInt("id", 10001);
        //}
        //Screne();
    }
    public void DownTimerClick()
    {
        timer = 10;
        DownTimer.transform.gameObject.SetActive(true);
        DownTimer.text = "倒计时:"+timer.ToString();
        InvokeRepeating("Time_count", 2.0f, 1.0f);
    }
    void Time_count()
    {
        if (timer > 0)
        {
            timer--;
            DownTimer.text = "倒计时:" + timer.ToString();
        }
        else {
            CancelInvoke();
        }
    }
	// Update is called once per frame
	void Update () {

        CurrentLevel.text = "第" + PlayerPrefs.GetInt( "id", 0 ) + "/" + configDictionaryLength;
        CoinNum.text = ":" + PlayerPrefs.GetInt( "coin", 0 ).ToString();
        if( answerK == answers.Length )
        {
            string inputAnswer = string.Empty;
            for( int i = 0; i < answers.Length; i++ )
            {
                inputAnswer += answerPanel.transform.Find( "answerItem" + i + "/Label" ).GetComponent<UILabel>().text;
            }
            Debug.Log( "答案" + inputAnswer );
            VerifyAnswer( inputAnswer );
        }
        //if (answerPanel.transform.Find( "answerItem"+answers.Length + "/Label").GetComponent<UILabel>().text != string.Empty)
        //{
        //    string inputAnswer = Answer1.transform.Find("Label").GetComponent<UILabel>().text + Answer2.transform.Find("Label").GetComponent<UILabel>().text + Answer3.transform.Find("Label").GetComponent<UILabel>().text + Answer4.transform.Find("Label").GetComponent<UILabel>().text;
        //    VerifyAnswer(inputAnswer);
        //}

    }
    //获取屏蔽分辨率
    public void Screne()
    {
        width = Screen.width;
        height = Screen.height;
        Debug.LogError( "width:" + width + "height:" + height );
    }
    public void readConfig()
    {
        Debug.Log(PlayerPrefs.GetInt("a"));
        TextAsset binAsset = Resources.Load( "config/chengyu", typeof( TextAsset ) ) as TextAsset;
        //Debug.Log( binAsset.text );
        //获取配置表的行
        string[] configdata =  binAsset.text.Split('\n');
        
        foreach (var data in configdata)
        {
            //Debug.Log(data);
            ConfigDataStyle configdat = new ConfigDataStyle();
            string[] dath = data.ToString().Split(',');
            if (dath.Length >= 4)
            {
                string id = dath[0];
                configdat.res = dath[1];
                configdat.answer = dath[2];
                configdat.disturb = dath[3];
                configDictionary.Add(id, configdat);
            }          
        }
        int len = (int)configdata.Length-2;
        Debug.Log("len" + len);      
        
        configDictionaryLength = int.Parse(configdata[configdata.Length-2].Split(',')[0]);
        ConfigFirstId = int.Parse( configdata[1].Split( ',' )[0] );    
        Debug.Log( "ConfigFirstId" + ConfigFirstId.ToString() );
        Debug.Log("configDictionaryLength" + configDictionaryLength);
        Debug.Log(configDictionary.Count);
        Debug.Log("res" + configDictionary["id"].answer);
        
      
        //res.mainTexture=TextAssetToTexture("chengyu/res/");
        //InitDisturbItem("1");
        GetIntId = PlayerPrefs.GetInt( "id", ConfigFirstId );       
        CoinNum.text = ":"+PlayerPrefs.GetInt( "coin", 0 ).ToString();
        InitConfig( GetIntId );
        PlayerPrefs.SetInt("id", GetIntId);
    }
    public void ChengYuStart()
    {
        InitConfig( GetIntId );
    }
    public class ConfigDataStyle
    {
        public string res;
        public string answer;
        public string disturb;
    }
    public void InitConfig(int id)
    {
        if (id <= configDictionaryLength)
        {
            string idNo = id.ToString();
            res.mainTexture = TextAssetToTexture("chengyu/res/" + configDictionary[idNo].res);
            Answer = configDictionary[idNo].answer;
            InitAnswerItem( Answer );
            //InitDisturbItem(configDictionary[idNo].disturb + "&" + configDictionary[idNo].answer);
            //int i = 18 - answersLength;
            string disturbString = string.Empty;
            for( int i = 18 - answersLength; i > 0; i-- )
            {
                int RandIndex = UnityEngine.Random.Range( 1, 30 );
                disturbString += "&" + DisturbList[RandIndex];
            }
            InitDisturbItem( configDictionary[idNo].answer + disturbString );
        }        
    }
    public void InitAnswerItem(string answerText)
    {
        answerK = 0;
        if( answerText == string.Empty )
        {
            return;
        }
        answers = answerText.Split( '&' );
        answersLength = answers.Length;
        for( int i = 0; i < answers.Length; i++ )
        {
            GameObject go = Instantiate( answerItem );
            go.transform.Find( "Label" ).GetComponent<UILabel>().text = string.Empty;
            go.transform.parent = answerPanel.transform;
            go.transform.name = "answerItem" + i;
            if( answers.Length == 1 )
            {
                go.transform.localPosition = new Vector3( 0, -49, 0 );
                go.transform.localScale = new Vector3( 1, 1 );
            }
            else if( answers.Length == 2 )
            {
                go.transform.localPosition = new Vector3( -60 + i * 120, -49, 0 );
                go.transform.localScale = new Vector3( 1, 1 );
            }
            else if( answers.Length == 3 )
            {
                go.transform.localPosition = new Vector3( -120 + i * 120, -49, 0 );
                go.transform.localScale = new Vector3( 1, 1 );
            }
            else if( answers.Length == 4 )
            {
            
                go.transform.localPosition=new Vector3( -190 + i * 120, -49, 0 );
                go.transform.localScale = new Vector3( 1, 1 );
            }
            else if( answers.Length == 5 )
            {
                go.transform.localPosition = new Vector3( -250 + i * 120, -49, 0 );
                go.transform.localScale = new Vector3( 1, 1 );
            }
        }

    }
    public void InitDisturbItem(string disturbText)
    {
        
        if (disturbText == string.Empty)
        {
            return;
        }
        Debug.Log( disturbText );
        string[] disturbs= RandArray(disturbText.Split('&'));
        float x=disturbItem.transform.localPosition.x;
        float y = disturbItem.transform.localPosition.y;
       
        GameObject[] allChildrenGameObject = GameObject.FindGameObjectsWithTag("disturbItem");
        if (allChildrenGameObject.Length >= 18)
        {
            for (int i = 0; i < 18; i++)
            {
                allChildrenGameObject[i].transform.Find("Label").GetComponent<UILabel>().text = disturbs[i];
                allChildrenGameObject[i].transform.Find("Label").gameObject.SetActive(true);
            }
        }
        else
        {
            for (int i = 0; i < 18; i++)
            {
                GameObject go = Instantiate(disturbItem);
                go.transform.Find("Label").GetComponent<UILabel>().text = string.Empty;
                go.transform.Find("Label").GetComponent<UILabel>().text = disturbs[i];
                go.transform.parent = disturbPanel.transform;
                if (i < 6)
                    go.transform.localPosition = new Vector3(x + 100 * i, y, 0f);
                else if (6 <= i && i < 12)
                    go.transform.localPosition = new Vector3(x + 100 * (i - 6), y - 110, 0f);
                else
                    go.transform.localPosition = new Vector3(x + 100 * (i - 12), y - 220, 0f);
                go.transform.localScale = Vector3.one;
            }
        }
        
    }
    public int AddAnswers(string answer)
    {
        if (answer == string.Empty)
            return 0;
        if( answersLength <= 0 )
        {
            return 0;
        }
        answersLength--;
        string lujin = "answerItem" + answerK.ToString() + "/Label";
        if( answerPanel.transform.Find( lujin ).GetComponent<UILabel>().text == string.Empty )
        {           
            answerPanel.transform.Find( lujin ).GetComponent<UILabel>().text = answer;
        }
        answerK++;
        //if (Answer1.transform.Find("Label").GetComponent<UILabel>().text == string.Empty)
        //{
        //    Answer1.transform.Find("Label").GetComponent<UILabel>().text = answer;
        //}
        //else if (Answer2.transform.Find("Label").GetComponent<UILabel>().text == string.Empty)
        //{
        //    Answer2.transform.Find("Label").GetComponent<UILabel>().text = answer;
        //}
        //else if (Answer3.transform.Find("Label").GetComponent<UILabel>().text == string.Empty)
        //{
        //    Answer3.transform.Find("Label").GetComponent<UILabel>().text = answer;
        //}
        //else if (Answer4.transform.Find("Label").GetComponent<UILabel>().text == string.Empty)
        //{
        //    Answer4.transform.Find("Label").GetComponent<UILabel>().text = answer;
        //}
        //else
        //{
        //    return 4;
        //}
        return 1;
    }
    public void RemoveAnswer(string answer)
    {
        
        GameObject[] allChildrenGameObject = GameObject.FindGameObjectsWithTag("disturbItem");
        //Debug.Log(allChildrenGameObject.Length);
        foreach (var childrenGameObject in allChildrenGameObject)
        {
            //Debug.Log(childrenGameObject.transform.Find("Label").GetComponent<UILabel>().text);
            if (childrenGameObject.transform.Find("Label").GetComponent<UILabel>().text == answer)
            {
                childrenGameObject.transform.Find("Label").gameObject.SetActive(true);
                continue;
            }
        }
    }

    public void VerifyAnswer(string inputAnswer)
    {
        string[] dicdata = Answer.Split('&');
        //string dicAnswer = dicdata[0] + dicdata[1] + dicdata[2] + dicdata[3];
        string dicAnswer = string.Empty;
        for( int i = 0; i <dicdata.Length; i++ )
        {
            dicAnswer += dicdata[i];
        }
        if (dicAnswer == inputAnswer)
        {
            Debug.Log("Answer is OK!");
            AudioManager.instance.AddCoinOnclick();

            TruePanel.SetActive( true );

            for( int i = 0; i < answers.Length; i++ )
            {               
                var go = GameObject.Find( "answerItem" + i );
                Destroy( go );
            }
            //PlayerPrefs.SetInt("id", PlayerPrefs.GetInt("id") + 1);
            PrefabsId();
            RreshCoin();
            Debug.Log("！！！！！！！！！！！！"+PlayerPrefs.GetInt("id"));
            InitConfig((int)PlayerPrefs.GetInt("id"));
            //Answer1.transform.Find("Label").GetComponent<UILabel>().text = string.Empty;
            //Answer2.transform.Find("Label").GetComponent<UILabel>().text = string.Empty;
            //Answer3.transform.Find("Label").GetComponent<UILabel>().text = string.Empty;
            //Answer4.transform.Find("Label").GetComponent<UILabel>().text = string.Empty;

            
            //判断是否是抢答模式
            if( QiangDao )
            {
                DownTimerClick();
            }    
        }
        else
        {
            AudioManager.instance.FalseOnclick();
            Debug.Log("Answer is error");
        }
    }
    public void NextProblmeOnClick()
    {
        if( LevelPanelManager.instance.UpdateLevelItemName == string.Empty )
        {
            LevelPanelManager.instance.UpdateLevelItemName = "LevelItemPanel0";
        }
        LevelPanelManager.instance.UpdateLevelLock(LevelPanelManager.instance.UpdateLevelItemName);
        LevelPanelManager.instance.UpdateTypeLock();
        TruePanel.SetActive( false );
        AudioManager.instance.errorAudio = true;
    }
    public void PrefabsId()
    {
        PlayerPrefs.SetInt("id", PlayerPrefs.GetInt("id") + 1);
    }
    public void RreshCoin()
    {
        if (timer > 0)
        {
            PlayerPrefs.SetInt("coin", PlayerPrefs.GetInt("coin") + 10); //如果在倒计时10秒内正确作答 加10个金币
        }
        else
        {
            PlayerPrefs.SetInt("coin", PlayerPrefs.GetInt("coin") + 5);
        }        
        CoinNum.text = ":"+PlayerPrefs.GetInt( "coin" ).ToString();
    }
    public static Texture TextAssetToTexture( string path )
    {
        TextAsset binAsset = Resources.Load( path, typeof( TextAsset ) ) as TextAsset;
        if( binAsset != null )
        {
            return byte2texture( binAsset.bytes );
        }
        return null;
    }
    public static Texture2D byte2texture( byte[] bytes )
    {
        if( bytes == null )
        {
            return null;
        }
        byte[] bytesdata = fAesEncrypt.Decrypt(bytes);
        Texture2D t2d;
        t2d = new Texture2D( 0, 0, TextureFormat.RGB24, false );
        t2d.LoadImage(bytesdata);
        t2d.wrapMode = TextureWrapMode.Clamp;
        return t2d;
    }

    //Random disturb
    public string[] RandArray(string[] disturb)
    {
        string[] newarr = new string[disturb.Length];
        int k = disturb.Length;    
        for (int i = disturb.Length - 1; i >= 0; i--)
        {
            int temp = new System.Random().Next(0, k);
            newarr[i] = disturb[temp];
            for (int j = temp; j < disturb.Length - 1; j++)
            {
                disturb[j] = disturb[j + 1];
            }
            k--;         
        }        
        return newarr;
    }
    public void exit()
    {

    }
    //提示面板的确定
    public void HintOnClick()
    {
        if( PlayerPrefs.GetInt( "coin", 0 ) >= 15 )
        {
            PlayerPrefs.SetInt( "coin", PlayerPrefs.GetInt( "coin" ) - 15 );
            MainPanelManager.instance.SetHintContent( 3, "第一个答案是"+answers[0] );
        }
        else
        {
            MainPanelManager.instance.SetHintContent( 2 );
            Debug.Log( "金币不足" );
        }
    }
    //干扰字符
    void InitDisturb()
    {
         DisturbList = new List<string> { "水","上","拖","伞","武","装","赛" ,"跑","帆","船","太","极","篮","球","足","中","跳","轮","软","排",
        "淌","厉","吉","马","风","划","拖","摩","模","特","殊","摔","跤"};
    }
}
